package com.siyu.common.utils.swmm;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.log.LogFactory;
import com.alibaba.fastjson2.JSONObject;
import com.siyu.common.constant.RehearsalConstants;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import java.io.*;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

public class SwwmUtil {

    private static Boolean kaiguan = false;//本地和部署

    private static Boolean pyswmmsh = false;//武汉和现场


    /**
     * swmm计算
     *
     * @param address
     * @return
     * @throws IOException
     */
    public static Object calculate(String address) throws IOException {
        LogFactory.get().info("swmm计算开始");
        if (kaiguan){
            Process process = null;
            if (RehearsalConstants.PORP3){
                process = new ProcessBuilder("python", "siyu-model/src/main/resources/swwm/runModel.py", address).redirectErrorStream(true).start();
            }else {
                process = new ProcessBuilder("python3", "siyu-model/src/main/resources/swwm/runModel.py", address).redirectErrorStream(true).start();
            }
            // 切割无用字符
            String results = readProcessOutput(process.getInputStream()).replace("swig/python detected a memory leak of type 'struct Handle *', no destructor found.", "").replace("'", "\"");
            // 找到 "Complete" 的位置
            int index = results.indexOf("Complete");
            if (index != -1) {
                // 截取 "Complete" 之后的内容
                LogFactory.get().info("swmm计算结束");
                return results.substring(index + "Complete".length());
            }
            LogFactory.get().info("swmm计算结束");
            return results;
        }else {
            String line;
            StringBuilder output = new StringBuilder();
            try {
                // 构建命令,更换inp文件
                String dockershell = "./run_docker.sh";
                String command = "";
                if (pyswmmsh){
                    command = "docker run --rm --volume /usr/local/bushu/siyumodel/siyu-model/src/main/resources/swwm:/app --workdir /app pyswmm:1.0 python3 /app/runModel.py "+address;
                }else {
                    command = "docker run --rm --volume /home/model/siyu-model/src/main/resources/swwm:/app --workdir /app pyswmm:1.0 python3 /app/runModel.py "+address;
                }

                xiugaidockershell(dockershell,command);
                // 执行run_docker.sh
                Process process = Runtime.getRuntime().exec(dockershell);

                // 获取输出流
                // 获取合并的输出流（stdout + stderr）
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
                    // 读取并打印输出（包括可能的错误信息）
                    while ((line = reader.readLine()) != null) {
                        output.append(line).append("\n");
                        System.out.println(line);
                    }
                }
                // 添加小延迟，确保所有输出都被发送
                Thread.sleep(1000); // 或者使用更合适的延迟时间
                // 等待进程结束
                int exitCode = process.waitFor();
                System.out.println("Process exited with code: " + exitCode);

                // 输出完整内容，包括可能的错误信息
                // 对输出进行后处理：移除特定错误信息，并提取"Complete"之后的内容
                String cleanedOutput = output.toString()
                        .replace("swig/python detected a memory leak of type 'struct Handle *', no destructor found.", "")
                        .replace("'", "\"");

                // 查找 "Complete" 的位置
                int index = cleanedOutput.indexOf("Complete");
                if (index != -1) {
                    // 截取 "Complete" 之后的内容
                    String resultsAfterComplete = cleanedOutput.substring(index + "Complete".length()).trim();
                    System.out.println("swmm结果（提取'Complete'后）: " + resultsAfterComplete);
                    return resultsAfterComplete;
                } else {
                    LogFactory.get().warn("输出中未找到 'Complete' 标记");
                    return cleanedOutput; // 如果未找到"Complete"，则返回原始处理后的输出
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            LogFactory.get().info("swmm计算结束");
            return output;
        }

    }

    public static void xiugaidockershell(String dockerShellPath,String command) {

        List<String> lines = new ArrayList<>();

        try (BufferedReader reader = new BufferedReader(new FileReader(dockerShellPath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                lines.add(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }

        // 修改第一行
        if (!lines.isEmpty()) {
            // 假设你想将第一行改为使用bash解释器
            lines.set(0, command);
        }

        // 写回文件
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(dockerShellPath))) {
            for (String modifiedLine : lines) {
                writer.write(modifiedLine);
                writer.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String readProcessOutput(InputStream inputStream) throws IOException {
        try (BufferedReader output = new BufferedReader(new InputStreamReader(inputStream))) {
            return output.lines().collect(Collectors.joining(""));
        }
    }



    public static void writeFile(List<Double> list, String url, Set<String> timeset, String[] arrayRefVar, JSONObject jsonObject, String dateTime, String type) throws IOException, ParseException {
        FileInputStream fis = new FileInputStream(url);
        HSSFWorkbook workbook = new HSSFWorkbook(fis);
        // 获取水位sheet和流量sheet
        HSSFSheet sheet1 = workbook.getSheet("水位");
        HSSFSheet sheet2 = workbook.getSheet("流量");
        // 定义写入位置
        int rowNum = 3;
        int colNum = 0;
        for (String time : timeset) {
            // 2019-09-13 01:00
            DateTime date = DateUtil.parse(time, "yyyy-MM-dd HH:mm");
            String formattedDateTime = DateUtil.format(date, "yyyy年M月d日H点");
            // 写入水位sheet
            HSSFRow row1 = sheet1.getRow(rowNum);
            if (row1 == null) {
                row1 = sheet1.createRow(rowNum);
            }
            HSSFCell cell1 = row1.createCell(colNum);
            cell1.setCellValue(formattedDateTime);
            // 写入流量sheet
            HSSFRow row2 = sheet2.getRow(rowNum);
            if (row2 == null) {
                row2 = sheet2.createRow(rowNum);
            }
            HSSFCell cell2 = row2.createCell(colNum);
            cell2.setCellValue(formattedDateTime);
            rowNum++;
        }
        // 写入校正后的水位
        for (int i = 0; i < arrayRefVar.length; i++) {
            // 开始行
            int wrowNum = 3;
            // 开始列
            int wcolNum = 1 + i;
            if (arrayRefVar[i].equals("xinglong") && type.equals("regulationup")) {
                for (Object s : list) {
                    HSSFRow row = sheet1.getRow(wrowNum);
                    if (row == null) {
                        row = sheet1.createRow(rowNum);
                    }
                    HSSFCell cell1 = row.createCell(wcolNum);
                    cell1.setCellValue(Double.valueOf(s.toString()));
                    wrowNum++;
                }
            } else {
                // 获取水位列表
                JSONObject shuiwei = jsonObject.getJSONObject(arrayRefVar[i]).getJSONObject("shuiwei");
                // 水位值
                Collection<Object> shuiweis = shuiwei.values();
                // 写入水位值
                for (Object s : shuiweis) {
                    HSSFRow row = sheet1.getRow(wrowNum);
                    if (row == null) {
                        row = sheet1.createRow(rowNum);
                    }
                    HSSFCell cell1 = row.createCell(wcolNum);
                    cell1.setCellValue(Double.valueOf(s.toString()));
                    wrowNum++;
                }
            }

            // 获取流量列表
            JSONObject liuliang = jsonObject.getJSONObject(arrayRefVar[i]).getJSONObject("liuliang");
            // 获取流量值
            Collection<Object> liuliangs = liuliang.values();
            // 开始行
            int frowNum = 3;
            // 开始列
            int fcolNum = 1 + i;
            // 写入流量值
            for (Object l : liuliangs) {
                HSSFRow row = sheet2.getRow(frowNum);
                if (row == null) {
                    row = sheet2.createRow(frowNum);
                }
                HSSFCell cell1 = row.createCell(fcolNum);
                cell1.setCellValue(Double.valueOf(l.toString()));
                frowNum++;
            }
        }
        // 调整列宽
        sheet1.autoSizeColumn(colNum);
        sheet2.autoSizeColumn(colNum);
        // 新建Excel文件，并写出
        File outFile = null;
        if (type.startsWith("regulation")) {
            outFile = new File("C:\\Users\\tiana\\Desktop\\preplay\\preplay\\regulation.xls");
//           outFile = new File(System.getProperty("user.dir")+"/sp/chaotu/sp/regulationfile/excel/"+ type + ".xls");
        } else {
            outFile = new File("C:\\Users\\tiana\\Desktop\\preplay\\warning\freeflow.xls");
//           outFile = new File(System.getProperty("user.dir")+"/sp/chaotu/sp/freeflowfile/excel/"+ type + ".xls");

        }
        if (outFile.exists()) outFile.delete();
        File outfileParentFile = outFile.getParentFile();
        if (!outfileParentFile.exists()) {
            outfileParentFile.mkdirs();
        }
        FileOutputStream fileOutputStream = new FileOutputStream(outFile);
        workbook.write(fileOutputStream);
        fileOutputStream.close();
        workbook.close();
        LogFactory.get().info("swmm结果生成exce结束");
    }

}



